package org.example.service.impl;

import org.example.Contant.BusinessException;
import org.example.dto.UpdateUserDto;
import org.example.dto.UserDto;
import org.example.entity.User;
import org.example.entity.UserRole;
import org.example.mapper.AccountMapper;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public List<UserDto> getAllUsers() {
        List<UserDto> users = accountMapper.getAllUsers();
        if (users.isEmpty()){
            throw new BusinessException("500","未查询到用户");
        }
        return users;
    }

    @Override
    public int deleteUserById(long id) {
        //删除用户表信息
        accountMapper.deleteUserById(id);
        //删除用户角色关联表信息
        accountMapper.deleteUserRoleById(id);
        return 1;
    }

    @Override
    public int update(UserDto userDto) {
        //修改用户表
        User user = new User();
        user.setId(userDto.getId());
        user.setUsername(userDto.getUsername());
        user.setPassword(userDto.getPassword());
        accountMapper.update(user);
        //修改用户角色关联表
        String role = userDto.getRole();
        int roleId = isUserOrAdmin(role);

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(roleId);
        accountMapper.updateUserRole(userRole);

        return 1;
    }

    @Override
    public int updateByUser(UpdateUserDto updateUserDto) {
        //校验原密码是否正确
        User user = accountMapper.selectUserById(updateUserDto.getId());
        if (!(user.getPassword().equals(updateUserDto.getOldPassword()))){
            throw new BusinessException("500","原密码错误");
        }
        if (!updateUserDto.getPassword().equals(updateUserDto.getNewPassword())){
            throw new BusinessException("500","两次密码不一致");
        }
        //修改用户
        User newUser = new User();
        newUser.setUsername(updateUserDto.getUsername());
        newUser.setPassword(updateUserDto.getNewPassword());
        accountMapper.update(newUser);
        return 1;
    }

    @Override
    public int add(UserDto userDto) {
        //新增用户
        User user = new User();
        user.setUsername(userDto.getUsername());
        user.setPassword(userDto.getPassword());

        accountMapper.addUser(user);
        //插入用户-角色关联表
        int roleId = isUserOrAdmin(userDto.getRole());
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(roleId);

        accountMapper.addUserRole(userRole);
        return 1;
    }

    /**
     * 判断是管理员还是普通用户
     * @param role
     * @return
     */
    public int isUserOrAdmin(String role){
        if ("user".equals(role)){
            return 2;
        }else
            return 1;
    }
}
